namespace RBAC.Write.Api.Application.Handler.QualityHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.QualityManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.QualityCommand;

    /// <summary>
    /// 新增质量工单附件 处理器
    /// </summary>
    public class QualityOrderAttachmentAddHandler : IRequestHandler<QualityOrderAttachmentAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<QualityOrderAttachment> _attRepo;
        private readonly IBaseRepository<QualityOrder> _orderRepo;
        private readonly ILogger<QualityOrderAttachmentAddHandler> _logger;

        public QualityOrderAttachmentAddHandler(
            IBaseRepository<QualityOrderAttachment> attRepo,
            IBaseRepository<QualityOrder> orderRepo,
            ILogger<QualityOrderAttachmentAddHandler> logger)
        {
            _attRepo = attRepo;
            _orderRepo = orderRepo;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(QualityOrderAttachmentAddCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (request.QualityOrderId <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "QualityOrderId无效", Data = 0 });

                // 校验主表存在
                var order = _orderRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.QualityOrderId });
                if (order == null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "质量工单不存在", Data = 0 });

                var entity = new QualityOrderAttachment
                {
                    QualityOrderId = request.QualityOrderId,
                    FileName = request.FileName,
                    FileUrl = request.FileUrl,
                    FileSize = request.FileSize,
                    ContentType = request.ContentType,
                    FileHash = request.FileHash,
                    UploadTime = DateTime.Now,
                    Status = 0,
                    Remark = request.Remark
                };
                if (!string.IsNullOrWhiteSpace(request.CreateUser))
                    entity.CreateUser = request.CreateUser!;

                var newId = _attRepo.Create(entity);
                result.Code = newId > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = newId > 0 ? "新增附件成功" : "新增附件失败";
                result.Data = newId;
            }
            catch (OperationCanceledException)
            {
                _logger?.LogWarning("新增质量工单附件被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "新增质量工单附件异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "新增质量工单附件异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
